﻿using System;
using NetSurveillance.WebApp.DataServices.Models;
using ServiceStack.OrmLite;

namespace NetSurveillance.WebApp.DataServices.Implementations
{
    public class DisplayFieldService : BaseService<DisplayField>
    {
        public DisplayFieldService(string connStr, IOrmLiteDialectProvider provider = null)
            : base(connStr, provider)
        {
        }

        public ServiceResult SaveAllFields(string[] fieldArr)
        {
            using (var db = DbFactory.OpenDbConnection())
            {
                db.Update<DisplayField>(new { StatusToken = 0 }, p => p.StatusToken == 1);
                if (fieldArr != null)
                    foreach (var field in fieldArr)
                    {
                        var fieldEntry = db.SingleWhere<DisplayField>("FieldName", field);
                        if (fieldEntry == null)
                            db.Insert(new DisplayField {FieldName = field, DisplayName = field});
                        else
                        {
                            fieldEntry.StatusToken = 1;
                            fieldEntry.LastModifiedTime = DateTime.Now;
                            db.Update(fieldEntry);
                        }
                    }
            }
            return ServiceResult.SuccessResult;
        }
    }
}